class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        int n = Math.max(text1.length(), text2.length()) + 1;
        // dp[i][j] 表示 text1 从 0 到 i 和 text2 从 0 到 j 的最长公共子序列的长度
        int[][] dp = new int[n][n];

        for (int i = 1; i <= text1.length(); i++) {
            for (int j = 1; j <= text2.length(); j++) {
                char c1 = text1.charAt(i - 1);
                char c2 = text2.charAt(j - 1);
                if (c1 == c2) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[text1.length()][text2.length()];
    }
}